﻿package commands 
{
	import flash.utils.ByteArray;
	import commands.classesinfo.*;
	
	/**
	 * ...
	 * @author wwx
	 */
	public final class BytesValueConverter 
	{
		
		public function BytesValueConverter() 
		{
			
		}
		
		private static var isBig:Boolean;
		public static function just():void
		{
			var value:int = 0x33221100;
			var bytes:ByteArray = new ByteArray();
			bytes.writeInt(value);
			if (0x00 == bytes[0] && 0x11 == bytes[1] 
				&& 0x22 == bytes[2] && 0x33 == bytes[3])
			{
				isBig = false;
				trace("BytesValueConverter is not big!");
			}
			else
			{
				isBig = true;
				trace("BytesValueConverter is big!");
			}
		}
		
		public static function writeIntToBytes(bytes:ByteArray, offset:int, value:int):void
		{
			bytes.position = offset;
			if (true == isBig)
			{
				bytes[offset + 0] = (value & 0xff);
				bytes[offset + 1] = ((value >> 8) & 0xff);
				bytes[offset + 2] = ((value >> 16) & 0xff);
				bytes[offset + 3] = ((value >> 24) & 0xff);	
				//bytes.position = offset + 4;
				//bytes.length = offset + 4;
			}
			else
			{
				//bytes.writeInt(value);
				bytes[offset + 0] = ((value >> 24) & 0xff);
				bytes[offset + 1] = ((value >> 16) & 0xff);
				bytes[offset + 2] = ((value >> 8) & 0xff);
				bytes[offset + 3] = (value & 0xff);
			}
			bytes.position = offset + 4;
			bytes.length = offset + 4;			
		}
		
		public static function writeShortToBytes(bytes:ByteArray, offset:int, value:int):void
		{
			bytes.position = offset;
			if (true == isBig)
			{
				bytes[offset + 0] = (value & 0xff);
				bytes[offset + 1] = ((value >> 8) & 0xff);
				bytes.position = offset + 2;
				bytes.length = offset + 2;
			}
			else
			{
				bytes.writeShort(value);
			}
		}
		
		public static function getIntFromBytes(bytes:ByteArray, offset:int):int
		{
			bytes.position = offset;
			var ret:int = -1;
			if (true == isBig)
			{
				ret = (int) (bytes[offset + 0]) + ((int(bytes[offset + 1])) << 8) + ((int(bytes[offset + 2])) << 16) + ((int(bytes[offset + 3])) << 24);
				bytes.position += 4;
			}
			else
			{
				ret = bytes.readInt();
			}
			return ret;
		}
		
	}
	
}